package com.xyz.update.update;

import static android.content.Context.NOTIFICATION_SERVICE;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import com.xyz.update.R;

public class NotificationUtils {
    public static final NotificationUtils instance = new NotificationUtils();
    private NotificationManager mManager;
    private NotificationCompat.Builder mBuilder;
    private final int NOTIFICATION_ID = 1;
    private final String CHANNEL_ID = "1";

    public void createNotification(Context context, int resLogo) {
        try {
            mManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "app update", NotificationManager.IMPORTANCE_LOW);
                mManager.createNotificationChannel(channel);
            }
            mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
                    .setContentTitle(context.getString(R.string.update_down_tips))
                    .setContentText(String.format(context.getString(R.string.update_down_progess), 0))
                    .setSmallIcon(resLogo)
                    .setOngoing(true)
                    .setProgress(100, 0, false)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true); // 是否自动消失
            mManager.notify(NOTIFICATION_ID, mBuilder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("StringFormatInvalid")
    public void updateNotification(Context context, int progress) {
        try {
            // 1.更新进度
            mBuilder.setContentText(String.format(context.getString(R.string.update_down_progess), progress))
                    .setProgress(100, progress, false);
            // 2.下载完成
            if (progress == 100) {
                mBuilder.setContentText(context.getString(R.string.update_down_over))
                        .setProgress(0, 0, false);
            }
            mManager.notify(NOTIFICATION_ID, mBuilder.build());
            if (progress == 100) {
                cancelNotification();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelNotification() {
        try {
            mManager.cancel(NOTIFICATION_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
